﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

public partial class Components_Product : System.Web.UI.UserControl
{
    DatabaseHelper helper;
    DBDataContext db;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Page.RouteData.Values["FunctionName"] != null) 
            {
                if (Page.RouteData.Values["Param"] != null)
                {

                    string ProductTypeID = Server.HtmlEncode(Utils.KillChars(Page.RouteData.Values["Param"].ToString()));
                    loadProductType(Convert.ToInt32(ProductTypeID));
                }
                else {
                    loadProductType(-1);
                }
            }
            
            //loadProduct();
        }
    }
    protected void btnOrder_Command(object sender, CommandEventArgs e)
    {
        try
        {
            //Dat hang
            if (e.CommandArgument != null)
            {
                /*TODO*/
                string str = e.CommandArgument.ToString();
                string[] arrListProduct = str.Split('@');
                int iProductID = Convert.ToInt32(arrListProduct[0]);
                string strProductName = arrListProduct[1];
                string strProductCode = arrListProduct[2];
                string strImagePath = arrListProduct[3];
                double dPrice = Convert.ToDouble(arrListProduct[4]);
                string strIsPromotion = arrListProduct[5];
                int iWeight = 1;
                createCartTable(iProductID, strProductName, strProductCode, strImagePath, dPrice, iWeight, Convert.ToInt32(strIsPromotion));
                Response.Redirect(Request.UrlReferrer.AbsolutePath, false);
            }
            else
            {
                /*TODO*/
                ControlUtil.LogError("Error Add To Cart Product Page");
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Add To Cart Product Page:" + ex.Message);
        }
    }
    #region Custom Method
    private void createCartTable(int iProductID, string strProductName, string strProductCode, string strImagePath, double dPrice, int iWeight, int iIsPromotion = 0)
    {
        try
        {
            DataTable dt;
            if (Session["ShoppingCart"] == null)//chua ton tai san pham trong Shopping Cart
            {
                dt = new DataTable();
                dt.Columns.Add("ProductID", System.Type.GetType("System.Int32"));
                dt.Columns.Add("IsPromotion", System.Type.GetType("System.Int32"));
                dt.Columns.Add("ProductName", System.Type.GetType("System.String"));
                dt.Columns.Add("ProductCode", System.Type.GetType("System.String"));
                dt.Columns.Add("ImagePath", System.Type.GetType("System.String"));
                dt.Columns.Add("Price", System.Type.GetType("System.Double"));
                dt.Columns.Add("Weight", System.Type.GetType("System.Int32"));
                dt.Columns.Add("Amount", System.Type.GetType("System.Double"));

                DataRow drNew = dt.NewRow();
                drNew["ProductID"] = iProductID;
                drNew["IsPromotion"] = iIsPromotion;
                drNew["ProductName"] = strProductName.Trim();
                drNew["ProductCode"] = strProductCode.Trim();
                drNew["ImagePath"] = strImagePath.Trim();
                drNew["Price"] = dPrice;
                drNew["Weight"] = iWeight;
                drNew["Amount"] = iWeight * dPrice;
                dt.Rows.Add(drNew);
            }
            else//Da co san pham trong ShoppingCart
            {
                dt = (DataTable)Session["ShoppingCart"];
                if (dt.Select("ProductID=" + iProductID).Count() > 0)//Chi thay doi Shopping Cart cua san pham da ton tai
                {
                    DataRow[] rowArr = dt.Select("ProductID=" + iProductID);
                    if (rowArr.Count() > 0)
                    {
                        DataRow row = rowArr[0];
                        row["Weight"] = Convert.ToInt32(row["Weight"].ToString().Replace(",", "")) + iWeight;//tang trong luong len 1
                        row["Amount"] = Convert.ToDouble(row["Amount"]) + (Convert.ToDouble(row["Price"]) * iWeight);// tinh lai thanh tien
                    }
                }
                else
                {
                    DataRow drNew = dt.NewRow();
                    drNew["ProductID"] = iProductID;
                    drNew["IsPromotion"] = iIsPromotion;
                    drNew["ProductName"] = strProductName.Trim();
                    drNew["ProductCode"] = strProductCode.Trim();
                    drNew["ImagePath"] = strImagePath.Trim();
                    drNew["Price"] = dPrice;
                    drNew["Weight"] = iWeight;
                    drNew["Amount"] = iWeight * dPrice;
                    dt.Rows.Add(drNew);
                }

            }
            Session["ShoppingCart"] = dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("CreateTable Product Page Home:" + ex.Message.ToString());
        }
        //return dt;
    }
    public DataTable loadProduct2(int iProductTypeID)
    {

        try
        {
            helper = new DatabaseHelper();

            System.Data.Common.DbParameter paramType = helper.Parameter;
            paramType.ParameterName = "IsNew";
            paramType.DbType = DbType.String;
            paramType.Value = "-1";
            helper.AddParameter(paramType);

            System.Data.Common.DbParameter paramProvinceID = helper.Parameter;
            paramProvinceID.ParameterName = "ProvinceID";
            paramProvinceID.DbType = DbType.Int32;
            paramProvinceID.Value = Convert.ToInt32(Session["ProvinceID"]);
            helper.AddParameter(paramProvinceID);


            System.Data.Common.DbParameter paramPageSize = helper.Parameter;
            paramPageSize.ParameterName = "PageSize";
            paramPageSize.DbType = DbType.Int32;
            paramPageSize.Value = 50;
            helper.AddParameter(paramPageSize);

            System.Data.Common.DbParameter paramProductTypeID = helper.Parameter;
            paramProductTypeID.ParameterName = "ProductTypeId";
            paramProductTypeID.DbType = DbType.Int32;
            paramProductTypeID.Value = iProductTypeID;
            helper.AddParameter(paramProductTypeID);

            System.Data.Common.DbParameter paramProductID = helper.Parameter;
            paramProductID.ParameterName = "ProductID";
            paramProductID.DbType = DbType.Int32;
            paramProductID.Value = -1;
            helper.AddParameter(paramProductID);

            System.Data.Common.DbParameter paramFunctionName = helper.Parameter;
            paramFunctionName.ParameterName = "FunctionName";
            paramFunctionName.DbType = DbType.String;
            paramFunctionName.Value = "chi-tiet-san-pham";
            helper.AddParameter(paramFunctionName);

            DataTable dt = helper.ExecuteDataTable("Web_GetProduct", CommandType.StoredProcedure, ConnectionState.CloseOnExit);
            return dt;
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Product Page-:loadProduct2" + ex.Message);
            return new DataTable();
        }
    }
    public IQueryable loadProduct(int iProductTypeID)
    {
        IQueryable obitsList = null;
        try
        {
            db = LINQUtil.GetDBWriteOnly();
            obitsList = (from a in db.Products
                         join b in db.ProductTypes on a.ProductTypeID equals b.ID 
                         where a.Status == 'A' && b.Status == 'A' && a.ProductType == "R" && b.ID == iProductTypeID
                         select new
                         {
                             ProductID = a.ID,
                             ProductTypeID = b.ID,
                             ProductTypeName = b.Name,
                             Link = "/chi-tiet-san-pham/" + a.ID + "/"  + a.ProductName.Replace(' ', '-').ToLower(),
                             ProductName = a.ProductName,
                             ProductCode = a.ProductCode,
                             Price = a.Price,
                             ImagePath = a.ImagePath

                         }).Take(4);

         //int t=   obitsList.AsQueryable().ToString().Count();
         if(obitsList == null)
             div_four.InnerHtml = "<B>Không tìm thấy sản phẩm</B>";
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Product Page-:loadProduct" + ex.Message);
        }
        return obitsList;
    }
    private void loadProductType(int iProductTypeId)
    {
        try
        {
            db = LINQUtil.GetDBWriteOnly();
            var query = (from a in db.ProductTypes
                         join  b in db.Products on a.ID  equals b.ProductTypeID
                         join c in db.DefinitionPrices on b.ID equals  c.ProductID
                         where a.Status == 'A' 
                                    && b.ProductType == "R" 
                                    && b.Status == 'A' 
                                    && (a.ID == iProductTypeId || iProductTypeId==-1)
                                    && c.LocationID == Convert.ToInt32(Session["ProvinceID"])
                         select new
                         {
                             ProductTypeName = a.Name,
                             ProductTypeId = a.ID
                             
                         }).Distinct().ToList();
            if (query.Count > 0)
            {
                DataTable dt = query.ToDataTable();
                lvProductType.DataSource = dt;
                lvProductType.DataBind();
            }
            else {
                div_four.InnerHtml = "<B>Không tìm thấy sản phẩm</B>";
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("Error Product Page-:loadProductType" + ex.Message);
        }
    }
    #endregion End Custom Method
    
}
